//引入方法
import { setToken ,getToken,removeToken} from "@/utils/auth"
//引入接口
import { login,getUserInfo } from "@/api/user"
//引入路由
import {constantRoutes,resetRouter} from '@/router'
const state = {
  token:getToken(),
  userInfo:{},
  routes:constantRoutes
}
const mutations = {
  LOGIN(state,value) {
    state.token = value
    setToken(value)
  },
  SETUSERINFO(state,value) {
    state.userInfo = value
  },
  //删除token
  REMOVETOKEN(state) {
    state.token = ''
    removeToken()
  },
  //合并路由
  MERGE_ROUTES(state,newRouter) {
    state.routes = [...constantRoutes,...newRouter]
  },
  //初始化路由
  INIT_ROUTES(state,newRouter) {
    state.routes = newRouter
    //重置路由
    resetRouter()
  }
}
const actions = {
  // 登录
 async login(context,data) {
   const token = await login(data)

    //发请求
    context.commit('LOGIN',token)
  },
  //获取用户信息
  async getUserInfo(comtext) {
    let reslut = await getUserInfo()
    comtext.commit('SETUSERINFO',reslut)
    return reslut
  },
  logout(comtext) {
 
    //删除token和用户信息
    comtext.commit('REMOVETOKEN')
    comtext.commit('SETUSERINFO',{})
    comtext.commit('INIT_ROUTES',constantRoutes)
  }
}
const getters = {}

export default {
  namespace: true,
  state,
  mutations,
  actions,
  getters
}